<template>
    <div>
      <el-row>
        <el-form :model="model" :rules="rules" ref="ruleForm" label-width="100px">
          <Portlet title="钱包 | 充值">

            <el-col :span="6" :offset="5">
              <el-form-item label="钱包余额:">
                <span class="font-red">{{totalMoney|decimalNumFilter}}</span> 元
              </el-form-item>
            </el-col>
            <el-col :span="6" :offset="2">
              <el-form-item label="充值金额:">
                <span class="font-red">{{money|decimalNumFilter}}</span> 元
              </el-form-item>
            </el-col>
          </Portlet>
          <Portlet title="充值方式">
            <el-col :span="10" :offset="6">
              <el-form-item
                label=""
                prop="paymentType"
              >
                <el-radio-group v-model="model.paymentType">
                  <el-tooltip :content=zhiTip :disabled="!zhiTip" placement="bottom" effect="light">
                    <el-radio-button :disabled="aliPayPC === false" v-for="(item, index) in paymentTypes" v-if="index === 0" :key="index" :label="item.value">
                      {{item.text}}
                      <!--{{aliPayPC}}-->
                    </el-radio-button>
                  </el-tooltip>
                  <el-tooltip :content=weTip :disabled="!weTip" placement="bottom" effect="light">
                    <el-radio-button :disabled="weChatPayPC === false" v-for="(item, index) in paymentTypes" v-if="index === 1" :key="index" :label="item.value">
                      {{item.text}}
                    </el-radio-button>
                  </el-tooltip>
                  <el-radio-button v-for="(item, index) in paymentTypes" v-if="index === 2" :key="index" :label="item.value">
                    {{item.text}}
                  </el-radio-button>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </Portlet>
        </el-form>
      </el-row>
      <el-row style="margin-top:20px;">
        <el-col :span="4" :offset="8">
          <el-button type="primary" @click.prevent="submit" :btnLoading="btnLoading" style="width:100%">确认充值</el-button>
        </el-col>
      </el-row>
      <el-dialog
        title="温馨提示"
        :visible.sync="payDialog"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :show-close="false"
        width="30%"
        center
      >
        <div style="text-align:center">请您在新打开的页面完成充值?</div>
        <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="unsuccessful">充值遇到问题</el-button>
        <el-button type="primary" @click="successful" :disabled="disabledBtn">
          {{ disabledBtn ? '等待充值结果' : '已经完成充值' }}</el-button>
          <!-- '(等待支付结果(' + timer + 's))' -->
      </span>
      </el-dialog>
    </div>
</template>
<script>
import {decimalNumFilter} from '@/filters'
import {range, isFormatNumber} from '@/utils/validate'
import {dotData} from '@/utils'
import {mapGetters, mapActions} from 'vuex'
export default {
  name: 'myWalletRecharge',
  data() {
    return {
      // tipText: '维护中请稍后重试',
      money: this.$route.params.inputMoney,
      totalMoney: this.$route.query.totalMoney,
      paymentTypes: [], // 支付方式array
      htmltext: '',
      paymentState: false,
      payDialog: false,
      btnLoading: false,
      disabledBtn: false,
      model: {
        paymentType: 'aliPay' // 默认：充支付宝
      },
      // 密码验证规则
      rules: {
        inputMoney: [
          { required: true, message: '请输入充值金额', trigger: 'change' },
          { validator: isFormatNumber, int: 8, decimal: 2, message: '请输入8位以下整数或2位小数', trigger: 'blur' },
          { validator: range, min: 0.01, message: '请输入大于0.01的正数', trigger: 'blur' }],
        paymentType: [
          {required: true, message: '充值方式必须', trigger: 'change'}
        ]}
    }
  },
  created() {
    // 支付方式
    this.paymentTypes = [
      {value: 'aliPay', text: '支付宝'},
      {value: 'weChatPay', text: '微　信'},
      {value: 'fastPay', text: '快捷支付'}
    ]
  },
  // mounted () {
  //   this.setRechargeResult({key: 'wallet', result: true})
  // },
  computed: {
    weTip() {
      if (this.weChatPayPC === false) {
        return '维护中请稍后再试'
      } else {
        return ''
      }
    },
    zhiTip() {
      if (this.aliPayPC === false) {
        return '维护中请稍后再试'
      } else {
        return ''
      }
    },
    // 计算出全局状态wallet的最新值
    rechargeResult() {
      return this.getRechargeResult('wallet')
    },
    // 读出配置 微信支付的最新值
    weChatPayPC() {
      return this.GET_GLOBAL_CONFIG('weChatPayPC')
    },
    // 读出配置 支付宝支付的最新值
    aliPayPC() {
      return this.GET_GLOBAL_CONFIG('aliPayPC')
    },
    ...mapGetters({'getRechargeResult': 'getRechargeResult', 'GET_GLOBAL_CONFIG': 'GET_GLOBAL_CONFIG'})
  },
  // 监听全局状态值的变化
  // 若为false,则payDialog=false,隐藏掉'提示模态框'
  watch: {
    rechargeResult(val, oldVal) {
      console.log('rechargeResult----', val)
      this.payDialog = val
    }
  },
  methods: {
    decimalNumFilter,
    isFormatNumber,
    range,
    submit() {
      this.$refs.ruleForm.validate().then((result) => {
        if (result) {
          const newWindow = window.open('/static/pay.html')
          this.btnLoading = true
          let postData = {}
          postData.money = this.money
          postData.type = this.model.paymentType
          this.$ajax.post('/ms-user-wallet/wallet/recharge', postData).then(response => {
            const success = dotData(response, 'success')
            if (success) {
              let temp = `<!DOCTYPE html>
                <html lang="en">
                <head>
                    <meta charset="UTF-8">
                    <title>Title</title>
                </head>
                <body>
                ${response.data.html}
                </body>
                </html>
                `
              newWindow.document.write(temp)
              newWindow.focus()
              // 改变vuex状态（赋新值：true）并传参：标识wallet，结果（只能传一个参 so用对象方式）
              this.setRechargeResult({key: 'wallet', result: true})
              this.disabledBtn = false // 已完成充值
            } else {
              newWindow.close()
            }
          }).catch(() => {
            newWindow.close()
          })
        } else {
          return false
        }
      })
    },
    unsuccessful() {
      this.payDialog = false
      this.$confirm('很抱歉！充值失败。您可以尝试重新支付或联系客服。', '温馨提示', {
        confirmButtonText: '重新充值',
        cancelButtonText: '联系客服',
        closeOnClickModal: false,
        type: 'warning',
        center: true
      }).catch(() => {
        // 联系客服
        this.btnLoading = false
      })
    },
    successful() {
      this.payDialog = false
      this.btnLoading = false
      this.$router.push({path: '/redirect/ss-fhb/myWallet/index'})
      console.log('OK11')
    },
    ...mapActions([
      'setRechargeResult'
    ])
  }
}
</script>
